package com.example.test.httpClient;

import cn.hutool.core.io.FileUtil;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class Main {

    public static void main(String[] args) throws IOException {
        File dir = new File("/home/wangbo/图片/testimage/50_face");
        File[] files = dir.listFiles();

        // 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();

        for (int i = 0; i < 50; i++) {
            search(files[i], httpClient, "lL9kXoZpKBoaTKTY6sZg0L5b75qHAo3U");
        }

    }

    private static String search(File file, CloseableHttpClient client, String token) throws IOException {
        // 配置连接
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)//一、连接超时：connectionTimeout-->指的是连接一个url的连接等待时间
                .setSocketTimeout(5000)// 二、读取数据超时：SocketTimeout-->指的是连接上一个url，获取response的返回等待时间
                .setConnectionRequestTimeout(5000)
                .build();

        // 创建httpEntity
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        String str = Base64.getEncoder().encodeToString(FileUtil.readBytes(file));
        params.add(new BasicNameValuePair("image-data", "data:image/jpeg;base64," + str));
        params.add(new BasicNameValuePair("calibrated-threshold", "50"));
        params.add(new BasicNameValuePair("tops", "1"));
        HttpEntity httpEntity = new UrlEncodedFormEntity(params, "utf-8");

        // 创建request
        String url = String.format("http://%s:%s/service/api/%s", "192.168.88.245", "8080", "search");
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Authorization", token);
        httpPost.setConfig(requestConfig);
        httpPost.setEntity(httpEntity);

        // 发送请求
        long begin = System.currentTimeMillis();
        CloseableHttpResponse response = client.execute(httpPost);
        long end = System.currentTimeMillis();

        // 解析响应结果
        String result = EntityUtils.toString(response.getEntity(), "utf-8");
        System.out.printf("耗时：%d%n", end - begin);
        System.out.println(result);
        return result;
    }
}
